package com.larry.isn;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.larry.util.LarryConst;
import com.pegatron.ers.logging.Checkin;
import com.pegatron.ers.logging.route.SfisQueryRoute;
import com.pegatron.ers.server.app.service.common.IProductService;
import com.pegatron.ers.util.StrUtil;
import com.pegatron.ers.vo.product.Product;
import com.pegatron.ers.vo.product.ProductConfig;

public class IsnRunner extends Thread {

	private String serialNr;

	private IProductService pService;

	private ProductConfig config;

	private Recorder recorder;

	public IsnRunner(String serialNr, IProductService pService, ProductConfig config, Recorder recorder) {
		this.serialNr = serialNr;
		this.pService = pService;
		this.config = config;
		this.recorder = recorder;
	}

	@Override
	public void run() {
		config.setRetreiverAsWebService(true);
		try {
			Product product = pService.getProduct(serialNr, config, new Checkin(new SfisQueryRoute()), true);
			if (StrUtil.isEmpty(product.getIsnInfo(Product.SHMAIN).getSsn()) && StrUtil.isEmpty(product.getIsnInfo(Product.SZMAIN).getSsn()) ) {
				this.writeFile("", LarryConst.FAIL_PATH);
			} else {
				this.writeFile("", LarryConst.CACHE_PATH);
			}
		} catch (Exception e) {
			e.printStackTrace();
//			this.writeFile(e.toString(), LarryConst.FAIL_PATH);
		} finally {
			recorder.callback();
		}
	}

	private void writeFile(String error, String path) {
		if (error == null) {
			return;
		}
		try {
			File file = new File(path);
			if (!file.exists()) {
				file.mkdir();
			}
			file = new File(path + serialNr + ".log");
			file.createNewFile();

			try {
				LarryFileWriter writer = new LarryFileWriter(file);
				List<String> list = new ArrayList<String>();
				list.add(error);
				writer.write(list);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
